#include "triangle.h"

#include <QtGui/QMatrix4x4>
#include <QtGui/QScreen>
#include <QMouseEvent>

#include "GL/glut.h"

Triangle::Triangle(QWidget *parent) : m_w(0.0f), m_x(1.0f), m_zoom(1.0), m_cubeSize(0.3), canMove(false), m_change(0)
{

}

void Triangle::initialize()
{
}

void Triangle::render()
{
    int n = 20;
    float x = -0.75 + m_w;
    float dx = (m_x-m_w) / (float)(n);

    glLoadIdentity();
    glScalef(m_zoom, m_zoom, m_zoom);
    glColor3f(1.0f, 0, 0);

    glBegin(GL_LINE_STRIP);
        glVertex3f(x, 0.0f, 0);
        x += dx;
        for(int i = 0; i < n; i++)
        {
            if(i % 2 == 0)
                glVertex3f(x, 0.1f, 0);
            else
                glVertex3f(x, -0.1f, 0);
            x += dx;
        }
        glVertex3f(x, 0.0f, 0);
    glEnd();

    float transl = x + 0.1;
    m_massPos = WorldToPixelsPoint(transl * m_zoom, 0);

    glTranslatef(transl, 0, 0);
    glutSolidCube(m_cubeSize);
}

void Triangle::update()
{
    updateGL();
}

void Triangle::updateX(float x)
{
    m_x = x;
}

void Triangle::updateW(float w)
{
    m_w = w;
}

void Triangle::mousePressEvent(QMouseEvent *e)
{
    // Save mouse press position
    if(!canMove)
    {
        mousePressPosition = QVector2D(e->localPos());

        QVector2D cubeHalfSize = WorldToPixelsLength((m_zoom*m_cubeSize)/4.0);
        if(mousePressPosition.x() <= m_massPos.x() + cubeHalfSize.x()
        && mousePressPosition.x() >= m_massPos.x() - cubeHalfSize.x()
        && mousePressPosition.y() <= m_massPos.y() + cubeHalfSize.y()
        && mousePressPosition.y() >= m_massPos.y() - cubeHalfSize.y())
        {
            canMove = true;
        }
    }
}

void Triangle::mouseReleaseEvent(QMouseEvent *e)
{
    if(canMove)
        emit x0changed();
    canMove = false;
}

void Triangle::mouseMoveEvent(QMouseEvent *event)
{
    if ((event->buttons() & Qt::LeftButton) && canMove) {
        QPoint pos = event->pos();
        m_x += PixelsToWorldLength(2.0 / m_zoom *(pos.x() - mousePressPosition.x())).x();
        mousePressPosition = QVector2D(event->localPos());
        event->accept();
    }
}

void Triangle::wheelEvent(QWheelEvent *event)
{
    int numDegrees = event->delta() / 8;
    int numSteps = numDegrees / 15;

    if(numSteps > 0)
        m_zoom += 0.1f;
    else if(numSteps < 0 && m_zoom > 0.1f)
        m_zoom -= 0.1f;


}


